import { _decorator, Component, Node, Prefab, instantiate, Vec3 } from 'cc';
import { GameConfig } from '../config/GameConfig';
import { Player } from '../entity/Player';

const { ccclass, property } = _decorator;

@ccclass('SceneManager')
export class SceneManager extends Component {
    @property(Node)
    private mapNode: Node = null;

    @property(Prefab)
    private playerPrefab: Prefab = null;

    @property([Node])
    private spawnPoints: Node[] = [];

    @property(Node)
    private entitiesNode: Node = null;

    private players: Player[] = [];

    start() {
        this.initScene();
    }

    private initScene() {
        // 初始化地图尺寸
        this.initMap();
        // 初始化出生点
        this.initSpawnPoints();
        // 生成测试玩家
        this.spawnPlayer();
    }

    private initMap() {
        // 设置地图尺寸
        const mapSize = GameConfig.GAME.MAP_SIZE;
        this.mapNode.setScale(new Vec3(mapSize, 1, mapSize));
    }

    private initSpawnPoints() {
        // 根据配置生成出生点位置
        const radius = GameConfig.GAME.MAP_SIZE / 3;
        const pointCount = GameConfig.GAME.MAX_PLAYERS;
        
        for (let i = 0; i < pointCount; i++) {
            const angle = (i / pointCount) * Math.PI * 2;
            const x = Math.cos(angle) * radius;
            const z = Math.sin(angle) * radius;
            
            const spawnPoint = new Node('SpawnPoint');
            spawnPoint.setPosition(new Vec3(x, 0, z));
            this.spawnPoints.push(spawnPoint);
            this.mapNode.addChild(spawnPoint);
        }
    }

    public spawnPlayer() {
        if (!this.playerPrefab) {
            console.error('Player prefab not set!');
            return;
        }

        // 随机选择一个出生点
        const spawnPoint = this.getRandomSpawnPoint();
        const playerNode = instantiate(this.playerPrefab);
        playerNode.setPosition(spawnPoint.position);
        this.entitiesNode.addChild(playerNode);

        const player = playerNode.getComponent(Player);
        this.players.push(player);

        return player;
    }

    private getRandomSpawnPoint(): Node {
        const index = Math.floor(Math.random() * this.spawnPoints.length);
        return this.spawnPoints[index];
    }
} 